<template>
  <view class="login-container">
    <view class="card-container">
      <!-- 顶部登录标题区 -->
      <view class="title-area" v-if="isLoginMode">
        <text class="welcome-text">欢迎来到</text>
        <text class="brand-text">
          <text class="brand-name">M</text>
          <text class="brand-name">o</text>
          <text class="brand-name">d</text>
          <text class="brand-name">i</text>
          <text class="brand-o">o</text>
          <text class="brand-text-normal">平台</text>
        </text>
        <view class="title-line"></view>
      </view>
        <!-- 顶部注册标题区 -->
      <view class="title-area" v-else>
        <text class="brand-text">
          <text class="brand-text-normal">创建新账户</text>
        </text>
        <view class="title-line"></view>
      </view>

      <!-- 登录表单 -->
      <view class="form-container" v-if="isLoginMode">
        <view class="input-item" :class="{'error': errors.username}">
          <text class="icon">👤</text>
          <input 
            type="text" 
            placeholder="用户名 / 邮箱" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.username"
            @blur="validateUsername"
          />
        </view>
        <text v-if="errors.username" class="error-text">{{ errors.username }}</text>

        <view class="input-item" :class="{'error': errors.password}">
          <text class="icon">🔒</text>
          <input 
            type="password" 
            placeholder="密码" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.password"
            @blur="validatePassword"
          />
        </view>
        <text v-if="errors.password" class="error-text">{{ errors.password }}</text>

        <view class="options-row">
          <view class="checkbox-item">
            <checkbox 
              :checked="rememberMe" 
              @change="handleRememberMeChange"
              color="#FF6B9B" 
            />
            <text class="checkbox-text">下次自动登录</text>
          </view>
          <text class="forget-password" @tap="handleForgetPassword">忘记密码</text>
        </view>

        <button class="action-button" @tap="handleLogin">登录</button>

        <view class="switch-link">
          <text class="switch-text">您还没有账户？</text>
          <text class="switch-action" @tap="toggleMode">去注册</text>
        </view>
      </view>

      <!-- 注册表单 -->
      <view class="form-container" v-else>

        <view class="input-item" :class="{'error': errors.username}">
          <text class="icon">👤</text>
          <input 
            type="text" 
            placeholder="用户名 / 邮箱" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.username"
            @blur="validateUsername"
          />
        </view>
        <text v-if="errors.username" class="error-text">{{ errors.username }}</text>

        <view class="input-item" :class="{'error': errors.phone}">
          <text class="icon">📱</text>
          <input 
            type="text" 
            placeholder="手机号" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.phone"
            @blur="validatePhone"
          />
        </view>
        <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>

        <view class="input-item" :class="{'error': errors.password}">
          <text class="icon">🔒</text>
          <input 
            type="password" 
            placeholder="密码" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.password"
            @blur="validatePassword"
          />
        </view>
        <text v-if="errors.password" class="error-text">{{ errors.password }}</text>

        <view class="input-item" :class="{'error': errors.confirmPassword}">
          <text class="icon">🔑</text>
          <input 
            type="password" 
            placeholder="确认密码" 
            placeholder-style="color: #999; font-size: 28rpx;"
            v-model="form.confirmPassword"
            @blur="validateConfirmPassword"
          />
        </view>
        <text v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</text>

        <view class="agreement-row">
          <checkbox 
            :checked="agreed" 
            @tap="handleAgreementChange"
            color="#FF6B9B" 
          />
          <text class="agreement-text">
            我已阅读并接受
            <text class="agreement-link" @tap="openUserAgreement">用户协议</text>
            和
            <text class="agreement-link" @tap="openPrivacyPolicy">隐私政策</text>
          </text>
        </view>

        <button class="action-button" @tap="handleRegister">注册</button>

        <view class="switch-link">
          <text class="switch-text">已经是会员？</text>
          <text class="switch-action" @tap="toggleMode">去登陆</text>
        </view>
      </view>
    </view>
  </view>
  
  <!-- 登录/注册加载弹窗 -->
  <view class="loading-mask" v-if="isLoading">
    <view class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">{{loadingText}}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { apiService, ApiService } from '/pages/utils/api.js'
import { useUserStore } from '/pages/store/user.js'
import StorageUtil from '/pages/utils/storage.js'

// 响应式数据
const isLoginMode = ref(true)
const form = reactive({
  username: '',
  password: '',
  phone: '',
  confirmPassword: ''
})
const errors = reactive({
  username: '',
  password: '',
  phone: '',
  confirmPassword: ''
})

// 记住我
const rememberMe = ref(false)

// 同意应用协议
const agreed = ref(false)

// 加载状态
const isLoading = ref(false)
const loadingText = ref('登录中...')

// 用户状态管理
const userStore = useUserStore()

// 页面加载时检查自动登录
onLoad(() => {
  console.log('登录页面加载')
  checkAutoLogin()
})

// 检查自动登录
const checkAutoLogin = () => {
  try {
    // 恢复"记住我"状态
    const savedRememberMe = StorageUtil.get('rememberMe', false)
    rememberMe.value = savedRememberMe
    
    // 初始化用户状态
    userStore.initUserState()
    
    // 如果用户选择了记住我且有有效的登录状态，自动跳转
    if (savedRememberMe && userStore.hasLogin) {
      console.log('检测到有效登录状态，自动跳转')
      uni.showToast({
        title: '自动登录成功',
        icon: 'success',
        duration: 1000
      })
      
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/tabs/project/index'
        })
      }, 1000)
    } else if (savedRememberMe && !userStore.hasLogin) {
      console.log('记住我已设置但登录状态已过期，清除记住我状态')
      StorageUtil.remove('rememberMe')
      rememberMe.value = false
    } else {
      console.log('用户未选择记住我，显示登录页面')
    }
  } catch (error) {
    console.error('自动登录检查失败:', error)
  }
}

// 方法定义
const toggleMode = () => {
  isLoginMode.value = !isLoginMode.value
  clearForm()
}

const clearForm = () => {
  form.username = ''
  form.password = ''
  form.phone = ''
  form.confirmPassword = ''
  errors.username = ''
  errors.password = ''
  errors.phone = ''
  errors.confirmPassword = ''
}

const validateUsername = () => {
  if (!form.username.trim()) {
    errors.username = '请输入用户名'
    return false
  }
  errors.username = ''
  return true
}

const validatePassword = () => {
  if (!form.password.trim()) {
    errors.password = '请输入密码'
    return false
  }
  errors.password = ''
  return true
}

const validatePhone = () => {
  if (!form.phone.trim()) {
    errors.phone = '请输入手机号'
    return false
  }
  
  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(form.phone.trim())) {
    errors.phone = '请输入正确的手机号格式'
    return false
  }
  
  errors.phone = ''
  return true
}

const validateConfirmPassword = () => {
  if (!form.confirmPassword.trim()) {
    errors.confirmPassword = '请输入确认密码'
    return false
  }
  if (form.confirmPassword !== form.password) {
    errors.confirmPassword = '两次密码不一致'
    return false
  }
  errors.confirmPassword = ''
  return true
}

const handleLogin = async () => {
  if (!validateUsername() || !validatePassword()) {
    return
  }
  
  try {
    // 设置加载状态
    isLoading.value = true
    loadingText.value = '登录中...'
    
    const res = await apiService.getFilterRows({
      worksheetId: ApiService.WORKSHEETENUM.USER,
      filters: [
        {
          "controlId": "68a6b776096ba6d65c500839",
          "dataType": 2,
          "spliceType": 1,
          "filterType": 2,
          "value": form.username
        },
        {
          "controlId": "68a6b776096ba6d65c50083a",
          "dataType": 2,
          "spliceType": 1,
          "filterType": 2,
          "value": form.password
        }
      ]
    })

    console.log('登录响应:', res)
    
    const isSuccess = Array.isArray(res.rows) && res.rows.length > 0

    if (isSuccess) {
      const userRowid = res.rows[0]['rowid']
      const userInfo = res.rows[0]
      
      console.log('登录成功，用户rowid:', userRowid)
      console.log('用户信息:', userInfo)
      
      // 保存用户信息和rowid到全局状态
      userStore.login(userInfo, userRowid)
      
      // 保存"记住我"状态
      StorageUtil.set('rememberMe', rememberMe.value)
      
      // 关闭加载状态
      isLoading.value = false
      
      // 显示成功提示
      uni.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500
      })
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/tabs/project/index'
        })
      }, 1500)
      
    } else {
      isLoading.value = false
      uni.showToast({
        title: '用户名或密码错误',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('登录失败:', error)
    isLoading.value = false
    uni.showToast({
      title: '登录失败，请重试',
      icon: 'none'
    })
  }
}

const handleRegister = async () => {
  
  if (!validateUsername() || !validatePassword() || !validatePhone() || !validateConfirmPassword()) {
    return
  }
  
  // 确保agreed是布尔值，处理可能的字符串值
  const isAgreed = Boolean(agreed.value) && agreed.value !== 'false'
  
  if (!isAgreed) {
    uni.showToast({
      title: '请同意用户协议和隐私政策',
      icon: 'none'
    })
    return
  }
  
  // 设置加载状态
  isLoading.value = true
  loadingText.value = '注册中...'

  const res = await apiService.getFilterRows({
      worksheetId: ApiService.WORKSHEETENUM.USER,
      filters: [
        {
          "controlId": "68a6b776096ba6d65c500839",
          "dataType": 2,
          "spliceType": 1,
          "filterType": 2,
          "value": form.username
        }
      ]
    })

    console.log('注册响应:', res)
    
    const isSuccess = Array.isArray(res.rows) && res.rows.length > 0

    if (isSuccess) {
      isLoading.value = false
      console.log('该用户名已被注册，请重新输入用户名')
      uni.showToast({
        title: '该用户名已被注册，请重新输入用户名',
        icon: 'none'
      })
      
    } else {
      console.log('该用户名未被注册，可以注册');
      
   // 关闭加载状态
   isLoading.value = false
       await apiService.register({
        worksheetId: ApiService.WORKSHEETENUM.USER,
        controls: [
          {
            "controlId": "68a6b776096ba6d65c500839",
            "value": form.username
          },
          {
            "controlId": "68a6b776096ba6d65c50083a",
            "value": form.password
          },
          {
            "controlId": "6886e725427a9931f8180b17",
            "value": form.phone
          },
          {
            "controlId": "ctime",
            "value": new Date()
          }
        ]
      })
      // 显示成功提示
      uni.showToast({
        title: '注册成功',
        icon: 'success',
        duration: 1500
      })
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/tabs/project/index'
        })
      }, 1500)

    
    }
}

const handleForgetPassword = () => {
  uni.showToast({
    title: '忘记密码功能开发中',
    icon: 'none'
  })
}

const openUserAgreement = () => {
  uni.showToast({
    title: '用户协议功能开发中',
    icon: 'none'
  })
}

const openPrivacyPolicy = () => {
  uni.showToast({
    title: '隐私政策功能开发中',
    icon: 'none'
  })
}

const handleAgreementChange = () => {
  console.log('agreed:', agreed.value);
  agreed.value = !agreed.value
  console.log('Updated agreed value:', agreed.value)
}

const handleRememberMeChange = () => {
  rememberMe.value = !rememberMe.value
  console.log('记住我状态:', rememberMe.value)
}
</script>

<style scoped>
  .login-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background: linear-gradient(135deg, #E8D5FF 0%, #FFB6C1 100%);
    padding: 0 32rpx;
  }

  .card-container {
    width: 85%;
    max-width: 600rpx;
    background: #FFFFFF;
    border-radius: 24rpx;
    box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
    padding: 48rpx 32rpx;
    margin: 48rpx 0;
  }

  .title-area {
    text-align: center;
    margin-bottom: 48rpx;
  }

  .welcome-text {
    font-size: 32rpx;
    color: #666666;
    display: block;
    margin-bottom: 16rpx;
  }

  .brand-text {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 48rpx;
    font-weight: bold;
    margin-bottom: 16rpx;
  }

  .brand-name {
    color: #000000;
  }

  .brand-o {
    color: #FF6B9B;
    position: relative;
    display: inline-block;
    width: 48rpx;
    height: 48rpx;
    background: #FF6B9B;
    border-radius: 50%;
    color: #FFFFFF;
    text-align: center;
    line-height: 48rpx;
    margin: 0 4rpx;
  }

  .brand-o::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 8rpx;
    height: 8rpx;
    background: #FFFFFF;
    border-radius: 50%;
  }

  .brand-text-normal {
    color: #666666;
    font-size: 32rpx;
    margin-left: 8rpx;
  }

  .title-line {
    width: 64rpx;
    height: 4rpx;
    background: #FF6B9B;
    margin: 8rpx auto 0;
    border-radius: 2rpx;
  }

  .register-title {
    font-size: 36rpx;
    color: #333333;
    font-weight: 500;
    margin-bottom: 32rpx;
  }

  .form-container {
    width: 100%;
  }

  .input-item {
    display: flex;
    align-items: center;
    background: #FFFFFF;
    border: 2rpx solid #E0E0E0;
    border-radius: 16rpx;
    padding: 0 24rpx;
    height: 104rpx;
    margin-bottom: 8rpx;
    transition: all 0.3s ease;
  }

  .input-item.error {
    border-color: #FF4D4F;
    border-width: 3rpx;
  }

  .icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 20rpx;
    opacity: 0.6;
  }

  input {
    flex: 1;
    font-size: 28rpx;
    color: #333333;
    height: 100%;
    border: none;
    outline: none;
  }

  .error-text {
    color: #FF4D4F;
    font-size: 24rpx;
    margin: 8rpx 0 16rpx 24rpx;
    display: block;
  }

  .options-row, .agreement-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 32rpx 0;
    font-size: 24rpx;
  }

  .checkbox-item {
    display: flex;
    align-items: center;
  }

  .checkbox-text {
    color: #666666;
    margin-left: 8rpx;
  }

  .forget-password {
    color: #1890FF;
    font-size: 24rpx;
  }

  .agreement-row {
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .agreement-text {
    color: #666666;
    font-size: 24rpx;
    margin-left: 8rpx;
    flex: 1;
  }

  .agreement-link {
    color: #1890FF;
    text-decoration: none;
  }

  .action-button {
    width: 100%;
    height: 96rpx;
    background: #FF6B9B;
    border: none;
    border-radius: 24rpx;
    color: #FFFFFF;
    font-size: 32rpx;
    font-weight: bold;
    margin: 32rpx 0;
    box-shadow: 0 4rpx 8rpx rgba(255, 107, 155, 0.3);
    transition: all 0.3s ease;
  }

  .action-button:active {
    transform: translateY(2rpx);
    box-shadow: 0 2rpx 4rpx rgba(255, 107, 155, 0.3);
  }

  .switch-link {
    text-align: center;
    margin-top: 32rpx;
  }

  .switch-text {
    color: #666666;
    font-size: 28rpx;
  }

  .switch-action {
    color: #FF6B9B;
    font-size: 28rpx;
    margin-left: 8rpx;
    font-weight: bold;
  }

  /* 加载弹窗样式 */
  .loading-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
  }

  .loading-container {
    background: #FFFFFF;
    border-radius: 24rpx;
    padding: 48rpx 64rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
  }

  .loading-spinner {
    width: 64rpx;
    height: 64rpx;
    border: 6rpx solid #F0F0F0;
    border-top: 6rpx solid #FF6B9B;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 24rpx;
  }

  .loading-text {
    font-size: 28rpx;
    color: #333333;
    font-weight: 500;
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
</style>